<template>
    <div class="content-box">
      <div ref="searchBox" class="search-box flex" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="70px"
        >
        <el-form-item label="产品名称" prop="productName">
          <el-input
            style="width: 240px; margin-right: 20px"
            v-model="queryParams.productName"
            placeholder="请输入"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="产品集合" prop="productIds">
            <el-select
              v-model="queryParams.productIds"
              multiple
              collapse-tags
              clearable
              filterable
              placeholder="请选择"
              style="width: 240px; margin-right: 20px"
            >
              <el-option
                v-for="(item, index) in downProductOptionList"
                :key="index"
                :label="item.productName"
                :value="item.id"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item
            label="下游公司"
            prop="companyIds"
          >
            <el-select
              v-model="queryParams.companyIds"
              multiple
              collapse-tags
              clearable
              filterable
              placeholder="请选择"
              style="width: 240px; margin-right: 20px"
            >
              <el-option
                v-for="(item, index) in downCompanyOptionList"
                :key="index"
                :label="item.companyName"
                :value="item.id"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="管理员" prop="manageUserIds">
            <el-select
              v-model="queryParams.manageUserIds"
              multiple
              collapse-tags
              clearable
              filterable
              placeholder="请选择"
              style="width: 240px; margin-right: 20px"
            >
              <el-option
                v-for="(item, index) in manageOptionList"
                :key="index"
                :label="item.userName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>

        <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              plain
              >查询</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="handelDialog('添加', null)"
              >添加配置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
  
      <div class="table-box">
        <el-row :gutter="10" class="mb8">
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="handleQuery"
            :columns="columns"
          ></right-toolbar>
        </el-row>
        <el-table
          v-sticky-header
          ref="table"
          v-loading="loading"
          :data="dataList"
        >
          <template v-for="(item,index) in columns.slice(0, columns.length - 1)">
            <el-table-column
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :width="getColumnWidth(index)"
              align="center"
              :fixed="item.fixed"
              :sortable="item.sortable ? item.sortable : false"
              :show-overflow-tooltip="item.showTooltip"
              v-if="item.visible"
            >
              <template slot-scope="scope">
                  <!-- 企微地址处理 -->
                  <div v-if="item.prop === 'weUrl'" 
                    style="cursor: pointer;"
                    v-clipboard:copy="scope.row[item.prop]" v-clipboard:success="clipboardSuccess">
                    {{  scope.row[item.prop] }}
                  </div>
                  <span v-else>
                    {{  scope.row[item.prop] }}
                   </span>
              </template>
            </el-table-column>
          </template>
          <el-table-column
            fixed="right"
            :prop="columns[columns.length - 1].prop"
            :label="columns[columns.length - 1].label"
            align="center"
            :width="getColumnWidth(columns.length - 1)"
            v-if="columns[columns.length - 1].visible"
          >
            <template slot-scope="scope">
              <div class="flex-center">
                <el-button
                  type="text"
                  @click="handelDialog('编辑', scope.row)"
                  >编辑</el-button
                >
                <el-popconfirm
                  title="确定要删除该配置吗？"
                  style="margin-left: 10px"
                  @cancel="hanCancelDel"
                  @confirm="handelDel(scope.row)"
                >
                  <el-button
                    slot="reference"
                    type="text"
                    ><span style="color: #ff116e">删除</span></el-button
                  >
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 使用分页插件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page-sizes="[10, 50, 100, 200, 500]"
          :page.sync="queryParams.pageIndex"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      <!-- 新增 对话框 -->
      <el-dialog
        :title="title"
        width="700px"
        :visible.sync="dialogShow"
        :before-close="handleClose"
      >
        <el-form :model="form" :rules="rules" label-width="100px" ref="formRef">
          <el-form-item
            label="下游产品"
            prop="productId"
            >
              <el-select
                v-model="form.productId"
                clearable
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in downProductOptionList"
                  :key="index"
                  :label="item.productName"
                  :value="item.id"
                ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="采量模式" prop="pickType">
            <el-select
              v-model="form.pickType"
              clearable
              filterable
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in pickTypeOption"
                :key="index"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计费模式" prop="feeType">
            <el-select
              v-model="form.feeType"
              clearable
              filterable
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in feeTypeOption"
                :key="index"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单价" prop="priceMoney">
              <el-input-number 
                v-model="form.priceMoney" 
                controls-position="right" 
                placeholder="请输入"
                :min="0" 
                style="width: 100%;"
              >
              </el-input-number>
          </el-form-item>
          <el-form-item label="企微地址" prop="weUrl">
            <el-input
              v-model="form.weUrl"
              style="width: 100%"
              placeholder="请输入企微地址"
              clearable
            />
          </el-form-item>
         
              
        </el-form>
        <div slot="footer" class="dialog-footer" >
          <el-button type="primary" @click="handleSubmit('formRef')"
            >确 定</el-button
          >
          <el-button @click="handleClose">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import tableStickyMixins from "@/mixins/tableStickyMixins";
  import { mapGetters } from "vuex";

  import {
    addOrEdit,
    deleteById,
    getFeeType,
    getPickType,
    queryById,
    queryDownWeChatConfigByPage
  } from "@/api/business/downWeChatConfig";
  import { querySysUserManageList } from "@/api/system/userManage";
  import { queryWeChatProductList } from "@/api/business/productManagement";
  import { getDwnCompanyList } from "@/api/business/downCompanyManagement";
  
  export default {
    // 定义名字用于标识该组件是否被keep-alive缓存
    name: "DownWeChatConfig",
    data() {
      return {
        // 数据列表
        dataList: [],
        // 下游产品筛选项
        downProductOptionList: [],
        // 计费模式筛选项
        feeTypeOption:[],
        // 采量模式筛选项
        pickTypeOption:[],
        // 管理人筛选项
        manageOptionList: [],
        // 下游公司筛选项
        downCompanyOptionList: [],
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          pageIndex: 1,
          pageSize: 10,
        },
        loading: false,
        // 表格列信息
        columns: [
          {label: `产品名称`,prop: "productName",visible: true,pcWidth: 'auto',mobileWidth: 100,fixed: null,showTooltip: true,},
          {label: `产品简称`,prop: "simpleName",visible: true,pcWidth: 'auto',mobileWidth: 100,fixed: null,showTooltip: true,},
          {label: `采量模式`,prop: "pickTypeStr",visible: true,pcWidth: 200,mobileWidth: 100,fixed: null,showTooltip: true,},
          {label: `计费模式`,prop: "feeTypeStr",visible: true,pcWidth: 200,mobileWidth: 100,fixed: null,showTooltip: true,},
          {label: `单价`,prop: "priceMoney",visible: true,pcWidth: 150,mobileWidth: 100,fixed: null,showTooltip: true,sortable: true,},
          {label: `企微地址`,prop: "weUrl",visible: true,pcWidth: 300,mobileWidth: 100,fixed: null,showTooltip: true,},
          {label: `产品管理员`,prop: "manageUserName",visible: true,pcWidth: 200,mobileWidth: 100,fixed: null,showTooltip: true,},
          {label: `操作`,prop: "operation",visible: true,pcWidth: 100,mobileWidth: 80,fixed: "right",showTooltip: true},
        ],
        // 显示搜索栏
        showSearch: true,
        // 弹框标题
        title: "",
        // 弹框显示状态
        dialogShow: false,
        // 弹框的表单信息
        form: {},
        // 弹框表单校验规则
        rules: {
        },
        
      };
    },
    mixins: [tableStickyMixins],
    watch: {
      columns: {
        handler() {
          this.updateTableHeight();
        },
        deep: true,
      },
    },
    created() {
      this.getList();
      this.getProductList();
      this.getRelatedType();
      this.getManageList();
      this.getCompanyOptionList();
    },
    computed: {
      ...mapGetters(["sidebar", "device"]),
      // 计算当前列元素在所处环境的宽度
      getColumnWidth() {
        return (index) => {
          return this.isMobile
            ? this.columns[index].mobileWidth
            : this?.sidebar?.opened
            ? this.columns[index].pcWidth - this.slightWidth
            : this.columns[index].pcWidth + 17;
        };
      },
    },
    methods: {
      /** 复制代码成功 */
      clipboardSuccess(text) {
        this.$modal.msgSuccess("复制成功,请粘贴使用");
      },
      // 获取公司筛选项列表
      getCompanyOptionList() {
        // 获取下游公司列表
        getDwnCompanyList().then((res) => {
          this.downCompanyOptionList = res.data;
        });
      },
      // 获取管理人列表
      getManageList() {
        querySysUserManageList().then((res) => {
           this.manageOptionList = res?.data;
        });
      },
      // 获取相关模式
      getRelatedType() {
          getFeeType().then((res) => {
            this.feeTypeOption = res?.data;
          });
          getPickType().then((res) => {
            this.pickTypeOption = res?.data;
          });
       },
      // 获取产品筛选项列表
      getProductList(){
        // 获取下游产品列表
        queryWeChatProductList().then((res) => {
          this.downProductOptionList = res.data;
        });
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.$set(this.queryParams, "pageIndex", 1);
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        // 完全重置到初始状态
        this.$set(this, "queryParams", {
          pageIndex: 1,
          pageSize: 10,
        });
        this.getList();
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        queryDownWeChatConfigByPage(this.queryParams).then((response) => {
          // 解决id为number类型精度丢失问题
          this.dataList = response?.data?.list
          this.total = response?.data?.total;
          this.loading = false;
        }).catch((err) => {
           setTimeout(() => {// 延迟2s后自动取消加载状态
             this.loading = false;
           }, 2000);
        })
      },
      // 修改表格高度触发回调
      updateTableHeight() {
        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
      },
      // 获取配置详细信息
      getConfigInfo(id){
        queryById(id).then((res) => {
          this.form = res.data;
        });
      },
      // 处理对话框
      handelDialog(title, row = null) {
        this.title = title + "配置";
        switch (title) {
            case "添加":
              break;
            case "编辑":
              // 获取配置详细信息回显数据
              this.getConfigInfo(row?.id);
              break;
            default:
           // 其他操作
        }
        this.dialogShow = true;
      },
      /*关闭弹窗*/
      handleClose() {
        this.$refs["formRef"].resetFields();
        this.form = this.$options.data().form;
        this.dialogShow = false;
      },
      // 取消删除
      hanCancelDel() {
        this.$message({
          type: "info",
          message: "已取消删除操作",
        });
      },
      // 删除列表项
      handelDel(row) {
        deleteById(row?.id).then((res) => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.getList();
          }
        });
      },
      // 刷新数据且关闭弹框
      handleRefresh() {
        // 刷新数据
        this.getList();
        // 关闭弹窗
        this.handleClose();
      },
      /*提交操作*/
      handleSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let params = {};
            params = JSON.parse(JSON.stringify(this.form));
            console.log(params);
            // 添加与编辑操作
            addOrEdit(params).then((res) => {
                 if (res.code === 200) {
                   this.$message.success(this.title=="添加配置"?"添加成功":"编辑成功");
                   this.handleRefresh();
                 }
            });
          }
        });
      },
    },
  };
  </script>
  
  <style scoped lang="scss">
  .title {
    font-size: 20px;
    color: #333333;
    font-weight: 500;
  }
  .search-box {
    margin: 0 0 20px;
    padding: 20px 20px 0;
    background: #fff;
    align-items: flex-start;
    border-radius: 6px;
  }
  .search-area {
    position: absolute;
    right: 20px;
  }
  .el-form-item__content {
    flex: 1;
    line-height: 40px;
    position: relative;
    font-size: 14px;
    min-width: 0;
  }
  ::v-deep .el-dialog__body {
    border-top: 1px solid #dfe6ec;
    border-bottom: 1px solid #dfe6ec;
  }
  .el-table {
    // 滚动条加粗
    --scrollbar-height: 9px;
  }
  </style>
  